package com.youlai.boot.task;

import com.youlai.boot.modules.content.mapper.LzArticleMapper;
import com.youlai.boot.modules.content.model.entity.LzArticle;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class LzArticleViewSyncTask {
    private final StringRedisTemplate redisTemplate;
    private final LzArticleMapper articleMapper;
    private static final String ARTICLE_VIEW_COUNT_KEY = "article:viewCount";

    // 初始化时从数据库同步浏览量到 Redis
    @PostConstruct
    public void init() {



        // 获取所有文章的浏览量
        List<LzArticle> articles = articleMapper.selectList(null);

        for (LzArticle article : articles) {

            Long articleId = article.getId();
            Long viewCount = article.getViewCount();

            if (viewCount != null) {
                // 设置浏览量，使用文章 ID 作为哈希中的字段，浏览量作为值
                redisTemplate.opsForHash().put(ARTICLE_VIEW_COUNT_KEY, String.valueOf(articleId), String.valueOf(viewCount));
                // 插入成功后，打印 Redis 中的值
                String value = (String) redisTemplate.opsForHash().get("article:viewCount", String.valueOf(articleId));
                System.out.println("Inserted value: " + value);  // 打印存入 Redis 中的值
            }
        }
    }

    @Scheduled(cron = "*/5 * * * * ?") // 每5秒执行一次
    public void syncViewCountToDatabase() {
        Map<Object, Object> viewCounts = redisTemplate.opsForHash().entries(ARTICLE_VIEW_COUNT_KEY);
        if (viewCounts.isEmpty()) {
            return;
        }

        for (Map.Entry<Object, Object> entry : viewCounts.entrySet()) {
            Long articleId = Long.valueOf(entry.getKey().toString());
            Long viewCount = Long.valueOf(entry.getValue().toString());

            // 更新数据库
            articleMapper.updateViewCount(articleId, viewCount);
        }

        // 删除 Redis 中已同步的数据
//        redisTemplate.delete(ARTICLE_VIEW_COUNT_KEY);

        log.info("文章浏览量已同步到数据库: {}", viewCounts);
    }
}